<template>
  <div class="statistics-overview">
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: color1 + '20', color: color1 }">
              <el-icon :size="24">
                <component :is="'House'" />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ safeGet(statistics, 'totalHousing', 0) }} 栋</div>
              <div class="stat-label">总楼宇</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: color2 + '20', color: color2 }">
              <el-icon :size="24">
                <component :is="'OfficeBuilding'" />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ safeGet(statistics, 'totalArea', 0) }} m²</div>
              <div class="stat-label">总面积</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: color3 + '20', color: color3 }">
              <el-icon :size="24">
                <component :is="'TrendCharts'" />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ safeGet(statistics, 'totalEnterprise', 0) }} 户</div>
              <div class="stat-label">入驻企业</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: color4 + '20', color: color4 }">
              <el-icon :size="24">
                <component :is="'User'" />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ (safeGet(statistics, 'occupancyRate', 0) * 100 || 0).toFixed(1) }} %</div>
              <div class="stat-label">出租率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <span class="font-semibold">信息统计</span>
          </template>
          <div class="area-distribution">
            <div class="stat-row">
              <span class="stat-label">已租赁面积</span>
              <span class="stat-value">{{ formatArea(safeGet(statistics, 'rentedArea', 0)) }} m² </span>
            </div>
            <div class="area-item">
              <span class="area-label">未租赁面积</span>
              <span class="area-value">{{ formatArea(safeGet(statistics, 'notRentedArea', 0)) }} m²</span>
            </div>
            <div class="area-item">
              <span class="area-label">即将到期面积</span>
              <span class="area-value text-success">{{ formatArea(safeGet(statistics, 'expiringSoonArea', 0)) }} m²</span>
            </div>
            <div class="area-item">
              <span class="area-label">即将到期企业</span>
              <span class="area-value text-warning">{{ safeGet(statistics, 'expiringSoonEnterprise', 0) }} 户</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 即将到期企业详情 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="flex items-center justify-between">
              <span class="font-semibold">即将到期企业详情</span>
              <el-tag type="danger" effect="plain"> {{ safeGet(statistics, 'expiringSoonEnterpriseDtoList.length', 0) }} 家企业即将到期 </el-tag>
            </div>
          </template>
          <el-table :data="safeGet(statistics, 'expiringSoonEnterpriseDtoList', [])" style="width: 100%" max-height="400">
            <el-table-column prop="enterpriseName" label="企业名称" />
            <el-table-column prop="totalArea" label="租赁面积(m²)">
              <template #default="scope">{{ formatArea(safeGet(scope.row, 'totalArea', 0)) }}</template>
            </el-table-column>
            <el-table-column prop="leaseEnd" label="到期日期">
              <template #default="scope">
                {{ formatDate(safeGet(scope.row, 'leaseEnd', '')) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { House, OfficeBuilding, TrendCharts, User } from '@element-plus/icons-vue';

import { overallStatistics } from '@/api/system/building';

// 统计数据
const statistics = ref<Record<string, any>>({});

const color1 = ref('#409eff');
const color2 = ref('#67C23A');
const color3 = ref('#E6A23C');
const color4 = ref('#909399');

// 安全获取对象属性值，避免undefined或null访问错误
const safeGet = (obj: any, path: string, defaultValue: any = 0) => {
  if (!obj || typeof obj !== 'object') return defaultValue;

  const keys = path.split('.');
  let result = obj;

  for (const key of keys) {
    if (result === null || result === undefined) {
      return defaultValue;
    }
    result = result[key];
  }

  return result === null || result === undefined ? defaultValue : result;
};

// 格式化面积
const formatArea = (area: number) => {
  if (area === undefined || area === null || isNaN(area)) {
    return '0';
  }
  return area.toLocaleString();
};

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  try {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN');
  } catch (error) {
    return dateStr;
  }
};

// 加载统计数据
const loadStatistics = async () => {
  try {
    const response = await overallStatistics({});
    if (response.code === 200) {
      statistics.value = response.data || {};
    }
  } catch (error) {
    console.error('加载统计数据失败:', error);
    // 提供默认数据避免页面空白
    statistics.value = {
      totalHousing: 0,
      totalArea: 0,
      totalEnterprise: 0,
      occupancyRate: 0,
      rentedArea: 0,
      notRentedArea: 0,
      expiringSoonArea: 0,
      expiringSoonEnterprise: 0,
      expiringSoonEnterpriseDtoList: []
    };
  }
};

onMounted(() => {
  loadStatistics();
});
</script>

<style scoped>
.statistics-overview {
  padding: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
}

.area-distribution,
.enterprise-stats {
  padding: 20px;
}

.area-item,
.stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.area-item:last-child,
.stat-row:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.area-label,
.stat-label {
  font-size: 14px;
}

.area-value,
.stat-value {
  font-size: 16px;
  font-weight: bold;
}

.text-success {
  color: #67c23a;
}

.text-warning {
  color: #e6a23c;
}

.text-primary {
  color: #409eff;
}

.text-danger {
  color: #f56c6c;
}

:deep(.el-progress-bar__outer) {
  border-radius: 10px;
}

:deep(.el-progress-bar__inner) {
  border-radius: 10px;
}
</style>
